<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>05-Promise入门详解</title>
  
    
      <meta 
        property="og:title" 
        content="05-Promise入门详解">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/05-Promise%E5%85%A5%E9%97%A8%E8%AF%A6%E8%A7%A3/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2006-06-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础异步">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81-Promise%EF%BC%9F"><span class="toc-text">为什么需要 Promise？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">回调的定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="toc-text">回调的缺点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E4%BB%8B%E7%BB%8D%E5%92%8C%E4%BC%98%E7%82%B9"><span class="toc-text">Promise 的介绍和优点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%94%A8%E6%B3%95%E5%92%8C%E7%8A%B6%E6%80%81"><span class="toc-text">Promise 对象的用法和状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Promise-%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%AD%A5%E9%AA%A4"><span class="toc-text">使用 Promise 的基本步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%AF%B9%E8%B1%A1%E7%9A%84-3-%E4%B8%AA%E7%8A%B6%E6%80%81"><span class="toc-text">promise 对象的 3 个状态</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%A0%E7%82%B9%E8%A1%A5%E5%85%85"><span class="toc-text">几点补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#new-Promise-%E6%98%AF%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81"><span class="toc-text">new Promise() 是同步代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E4%B8%80%E6%97%A6%E6%94%B9%E5%8F%98%EF%BC%8C%E5%B0%B1%E4%B8%8D%E8%83%BD%E5%86%8D%E5%8F%98"><span class="toc-text">Promise 的状态一旦改变，就不能再变</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E6%94%B9%E5%8F%98%EF%BC%8C%E6%98%AF%E4%B8%8D%E5%8F%AF%E9%80%86%E7%9A%84"><span class="toc-text">Promise 的状态改变，是不可逆的</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E8%A7%84%E8%8C%83"><span class="toc-text">Promise 规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="toc-text">Promise 封装定时器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">Promise 封装 Ajax 请求</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95-1"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95-1"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81%E7%9A%84%E4%B8%A4%E7%A7%8D%E5%86%99%E6%B3%95"><span class="toc-text">处理 reject 失败状态的两种写法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F"><span class="toc-text">代码格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%BE%E4%BE%8B"><span class="toc-text">代码举例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="toc-text">参考链接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      05-Promise入门详解
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2006-05-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2006-06-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
          class="post-meta-link">
          JS基础异步
        </a>
      
    
    
      <span class="dot"></span>
      <span>5.4k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
            class="post-meta-link">
            JS基础异步
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="为什么需要-Promise？"><a href="#为什么需要-Promise？" class="headerlink" title="为什么需要 Promise？"></a>为什么需要 Promise？</h2><p>我们在前面的文章《JavaScript 基础：异步编程和 Ajax&#x2F;单线程和异步》中讲过，Javascript 是⼀⻔单线程语⾔。早期我们解决异步场景时，⼤部分情况都是通过回调函数来进⾏。</p>
<p>（如果你还不了解单线程和异步的概念，可以先去回顾上一篇文章。）</p>
<h3 id="回调的定义"><a href="#回调的定义" class="headerlink" title="回调的定义"></a>回调的定义</h3><p>把函数 A 传给另一个函数 B 调用，那么函数 A 就是回调函数。</p>
<p>例如在浏览器中发送 ajax 请求，就是常⻅的⼀个异步场景，发送请求后，需要等待一段时间，等服务端响应之后我们才能拿到结果。如果我们希望在异步结束之后执⾏某个操作，就只能通过<strong>回调函数</strong>这样的⽅式进⾏操作。</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> dynamicFunc = <span class="keyword">function</span> (<span class="params">callback</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="title function_">callback</span>();</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="title function_">dynamicFunc</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qian gu&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre>

<p>例如上⾯这个例⼦，dynamicFunc 就是⼀个异步函数，⾥⾯ setTimeout 会在 1s 之后调⽤传⼊的 callback 函数。按照上⾯的调⽤⽅式，最终 1s 之后，会打印 qian gu 这个结果。</p>
<p>为了能使回调函数以更优雅的⽅式进⾏调⽤，在 ES6 语法中，新增了⼀个名为 Promise 的新规范。</p>
<h3 id="回调的缺点"><a href="#回调的缺点" class="headerlink" title="回调的缺点"></a>回调的缺点</h3><p>回调的写法比较直观，不需要 return，层层嵌套即可。但也存在两个问题：</p>
<ul>
<li><ol>
<li>如果嵌套过深，则会出现<strong>回调地狱</strong>的问题。</li>
</ol>
</li>
<li><ol start="2">
<li>不同的函数，回调的参数，在写法上可能不一致，导致不规范、且需要<strong>单独记忆</strong>。</li>
</ol>
</li>
</ul>
<p>我们来具体看看这两个问题。</p>
<p><strong>1、回调地狱的问题</strong>：</p>
<p>如果多个异步函数存在依赖关系（比如，需要等第一个异步函数执行完成后，才能执行第二个异步函数；等第二个异步函数执行完毕后，才能执行第三个异步函数），就需要多个异步函数进⾏层层嵌套，⾮常不利于后续的维护，而且会导致<strong>回调地狱</strong>的问题。</p>
<p>关于回调地狱，我们来举一个形象的例子：</p>
<blockquote>
<p>假设买菜、做饭、洗碗、倒厨余垃圾都是异步的。</p>
</blockquote>
<blockquote>
<p>但真实的场景中，实际的操作流程是：买菜成功之后，才能开始做饭。做饭成功后，才能开始洗碗。洗碗完成后， 再倒厨余垃圾。这里的一系列动作就涉及到了多层嵌套调用，也就是回调地狱。</p>
</blockquote>
<p>关于回调地狱，我们来看看几段代码举例。</p>
<p>1.1、定时器的代码举例：（回调地狱）</p>
<pre class="highlight"><span class="line"><span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qiangu1&#x27;</span>);</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qiangu2&#x27;</span>);</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qiangu3&#x27;</span>);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;, <span class="number">1000</span>);</span><br></pre>

<p>1.2、Node.js 读取文件的代码举例：（回调地狱）</p>
<pre class="highlight"><span class="line">fs.<span class="title function_">readFile</span>(A, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">    fs.<span class="title function_">readFile</span>(B, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">        fs.<span class="title function_">readFile</span>(C, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">            fs.<span class="title function_">readFile</span>(D, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">                <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao:&#x27;</span> + data);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre>

<p>上面代码的逻辑为：先读取 A 文本内容，再根据 A 文本内容读取 B，然后再根据 B 的内容读取 C。为了实现这个业务逻辑，上面的代码就很容易形成回调地狱。</p>
<p>1.3、ajax 请求的代码举例：（回调地狱）</p>
<pre class="highlight"><span class="line"><span class="comment">// 伪代码</span></span><br><span class="line"><span class="title function_">ajax</span>(<span class="string">&#x27;a.json&#x27;</span>, <span class="function">(<span class="params">res1</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res1);</span><br><span class="line">    <span class="title function_">ajax</span>(<span class="string">&#x27;b.json&#x27;</span>, <span class="function">(<span class="params">res2</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res2);</span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;c.json&#x27;</span>, <span class="function">(<span class="params">res3</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(res3);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre>

<p><strong>2、回调的写法不一致问题</strong>：</p>
<pre class="highlight"><span class="line"><span class="comment">// Node.js 读取文件时，成功回调和失败回调，是通过 error参数来区分</span></span><br><span class="line"><span class="title function_">readFile</span>(<span class="string">&#x27;d:\\readme.text&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (error) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;文件读取失败&#x27;</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;文件读取成功&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// jQuery的 ajax 写法中，成功回调和失败回调，是通过两个回调函数来区分</span></span><br><span class="line">$.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&#x27;/ajax.json&#x27;</span>,</span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">response</span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;文件读取成功&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">error</span>: <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;文件读取失败&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre>

<p>我们可以看到，上面的代码中，成功回调和失败回调，写法不统一，需要单独记忆，容易出错。</p>
<p><strong>小结</strong>：</p>
<p>在 ES5 中，当进行多层嵌套回调时，会导致代码层次过多，很难进行后续维护和二次开发；而且会导致<strong>回调地狱</strong>的问题。ES6 中的 Promise 就可以解决这些问题。</p>
<p>当然， Promise 的强大功能，不止于此。我们来一探究竟。</p>
<h3 id="Promise-的介绍和优点"><a href="#Promise-的介绍和优点" class="headerlink" title="Promise 的介绍和优点"></a>Promise 的介绍和优点</h3><p>ES6 中的 Promise 是异步编程的一种方案。从语法上讲，Promise 是一个对象，它可以获取异步操作的消息。</p>
<p>Promise 对象, 可以<strong>用同步的表现形式来书写异步代码</strong>（也就是说，代码看起来是同步的，但本质上的运行过程是异步的）。使用 Promise 主要有以下好处：</p>
<ul>
<li>1、可以很好地解决<strong>回调地狱</strong>的问题（避免了层层嵌套的回调函数）。</li>
<li>2、语法简洁、可读性强，便于后期维护。</li>
<li>3、Promise 对象提供了简洁的 API，使得管理异步操作更加容易。比如<strong>多任务等待合并</strong>。</li>
</ul>
<p>Promise 的伪代码结构，大概是这样的：</p>
<pre class="highlight"><span class="line"><span class="comment">// 伪代码1</span></span><br><span class="line"><span class="title function_">myPromise</span>()</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;,</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;</span><br><span class="line">    )</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;,</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;</span><br><span class="line">    )</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;,</span><br><span class="line">        <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line"><span class="comment">// 伪代码2</span></span><br><span class="line">是时候展现真正的厨艺了().然后(买菜).然后(做饭).然后(洗碗);</span><br></pre>

<p>上面的伪代码可以看出，即便在业务逻辑上是层层嵌套，但是代码写法上，却十分优雅，也没有过多的嵌套。</p>
<h2 id="Promise-对象的用法和状态"><a href="#Promise-对象的用法和状态" class="headerlink" title="Promise 对象的用法和状态"></a>Promise 对象的用法和状态</h2><h3 id="使用-Promise-的基本步骤"><a href="#使用-Promise-的基本步骤" class="headerlink" title="使用 Promise 的基本步骤"></a>使用 Promise 的基本步骤</h3><p>（1）通过 <code>new Promise()</code> 构造出一个 Promise 实例。Promise 的构造函数中传入一个参数，这个参数是一个函数，该函数用于处理异步任务。</p>
<p>（2）函数中传入两个参数：resolve 和 reject，分别表示异步执行成功后的回调函数和异步执行失败后的回调函数。代表着我们需要改变当前实例的状态到<strong>已完成</strong>或是<strong>已拒绝</strong>。</p>
<p>（3）通过 promise.then() 和 promise.catch() 处理返回结果（这里的 <code>promise</code> 指的是 Promise 实例）。</p>
<p>看到这里，你估计还是不知道 Promise 怎么使用。我们不妨来看一下 Promise 有哪些状态，便一目了然。要知道，Promise 的精髓在于<strong>对异步操作的状态管理</strong>。</p>
<h3 id="promise-对象的-3-个状态"><a href="#promise-对象的-3-个状态" class="headerlink" title="promise 对象的 3 个状态"></a>promise 对象的 3 个状态</h3><ul>
<li><p>初始化（等待中）：pending</p>
</li>
<li><p>成功：fulfilled</p>
</li>
<li><p>失败：rejected</p>
</li>
</ul>
<p><strong>步骤 1</strong>：</p>
<p>当 new Promise()执行之后，promise 对象的状态会被初始化为<code>pending</code>，这个状态是初始化状态。<code>new Promise()</code>这行代码，括号里的内容是同步执行的。括号里可以再定义一个 异步任务的 function，function 有两个参数：resolve 和 reject。如下：</p>
<ul>
<li><p>如果请求成功了，则执行 resolve()，此时，promise 的状态会被自动修改为 fulfilled。</p>
</li>
<li><p>如果请求失败了，则执行 reject()，此时，promise 的状态会被自动修改为 rejected</p>
</li>
</ul>
<p>（2）promise.then()方法：<strong>只有 promise 的状态被改变之后，才会走到 then 或者 catch</strong>。也就是说，在 new Promise()的时候，如果没有写 resolve()，则 promise.then() 不执行；如果没有写 reject()，则 promise.catch() 不执行。</p>
<p><code>then()</code>括号里面有两个参数，分别代表两个函数 function1 和 function2：</p>
<ul>
<li><p>如果 promise 的状态为 fulfilled（意思是：如果请求成功），则执行 function1 里的内容</p>
</li>
<li><p>如果 promise 的状态为 rejected（意思是，如果请求失败），则执行 function2 里的内容</p>
</li>
</ul>
<p>另外，resolve()和 reject()这两个方法，是可以给 promise.then()传递参数的。</p>
<p>关于 promise 的状态改变，以及如何处理状态改变，伪代码及注释如下：</p>
<pre class="highlight"><span class="line"><span class="comment">// 创建 promise 实例</span></span><br><span class="line"><span class="keyword">let</span> promise = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">//进来之后，状态为pending</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;同步代码&#x27;</span>); <span class="comment">//这行代码是同步的</span></span><br><span class="line">    <span class="comment">//开始执行异步操作（这里开始，写异步的代码，比如ajax请求 or 开启定时器）</span></span><br><span class="line">    <span class="keyword">if</span> (异步的ajax请求成功) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;333&#x27;</span>);</span><br><span class="line">        <span class="title function_">resolve</span>(<span class="string">&#x27;请求成功，并传参&#x27;</span>); <span class="comment">//如果请求成功了，请写resolve()，此时，promise的状态会被自动修改为fulfilled（成功状态）</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="title function_">reject</span>(<span class="string">&#x27;请求失败，并传参&#x27;</span>); <span class="comment">//如果请求失败了，请写reject()，此时，promise的状态会被自动修改为rejected（失败状态）</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;222&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用promise的then()：开始处理成功和失败</span></span><br><span class="line">promise.<span class="title function_">then</span>(</span><br><span class="line">    <span class="function">(<span class="params">successMsg</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 处理 promise 的成功状态：如果promise的状态为fulfilled，则执行这里的代码</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(successMsg, <span class="string">&#x27;成功了&#x27;</span>); <span class="comment">// 这里的 successMsg 是前面的 resolve(&#x27;请求成功，并传参&#x27;)  传过来的参数</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function">(<span class="params">errorMsg</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">//处理 promise 的失败状态：如果promise的状态为rejected，则执行这里的代码</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(errorMsg, <span class="string">&#x27;失败了&#x27;</span>); <span class="comment">// 这里的 errorMsg 是前面的 reject(&#x27;请求失败，并传参&#x27;) 传过来的参数</span></span><br><span class="line">    &#125;</span><br><span class="line">);</span><br></pre>

<p>上面的注释要多看几遍。</p>
<h2 id="几点补充"><a href="#几点补充" class="headerlink" title="几点补充"></a>几点补充</h2><h3 id="new-Promise-是同步代码"><a href="#new-Promise-是同步代码" class="headerlink" title="new Promise() 是同步代码"></a>new Promise() 是同步代码</h3><p><code>new Promise()</code>这行代码本身是同步的。promise 如果没有使用 resolve 或 reject 更改状态时，状态为 pending。</p>
<p><strong>举例 1</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> promiseA = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;&#125;);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(promiseA); <span class="comment">// 此时 promise 的状态为 pending（准备阶段）</span></span><br></pre>

<p>上面的代码中，我既没有写 reslove()，也没有写 reject()。也就是说，这个 promise 一直处于准备阶段。</p>
<p>当完成异步任务之后，状态分为成功或失败，此时我们就可以用 reslove() 和 reject() 来修改 promise 的状态。</p>
<p><strong>举例 2</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;promise1&#x27;</span>); <span class="comment">// 这行代码是同步代码，会立即执行</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;promise then:&#x27;</span> + res); <span class="comment">// 这行代码不会执行，因为前面没有写 resolve()，所以走不到 .then</span></span><br><span class="line">&#125;);</span><br></pre>

<p>打印结果：</p>
<pre class="highlight"><span class="line">promise1</span><br></pre>

<p>上方代码，仔细看注释：如果前面没有写 <code>resolve()</code>，那么后面的 <code>.then</code>是不会执行的。</p>
<p><strong>举例 3</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">resolve</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;promise1&#x27;</span>); <span class="comment">// 代码1：同步任务，会立即执行</span></span><br><span class="line">&#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;promise  then&#x27;</span>); <span class="comment">// 代码2：异步任务中的微任务</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;千古壹号&#x27;</span>); <span class="comment">// 代码3：同步任务</span></span><br></pre>

<p>打印结果：</p>
<pre class="highlight"><span class="line">promise1</span><br><span class="line">千古壹号</span><br><span class="line">promise  then</span><br></pre>

<p>代码解释：代码 1 是同步代码，所以最先执行。代码 2 是<strong>微任务</strong>里面的代码，所以要先等同步任务（代码 3）先执行完。当写完<code>resolve();</code>之后，就会立刻把 <code>.then()</code>里面的代码加入到微任务队列当中。</p>
<p>补充知识：异步任务分为“宏任务”、“微任务”两种。我们到后续的章节中再详细讲。</p>
<h3 id="Promise-的状态一旦改变，就不能再变"><a href="#Promise-的状态一旦改变，就不能再变" class="headerlink" title="Promise 的状态一旦改变，就不能再变"></a>Promise 的状态一旦改变，就不能再变</h3><p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> p = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">resolve</span>(<span class="number">1</span>); <span class="comment">// 代码执行到这里时， promise状态是 fulfilled</span></span><br><span class="line">    <span class="title function_">reject</span>(<span class="number">2</span>); <span class="comment">// 尝试修改状态为 rejected，是不行的。因为状态执行到上一行时，已经被改变了。</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">p.<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;).<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">&#125;);</span><br></pre>

<p>上方代码的打印结果是 1，而不是 2，详见注释。</p>
<h3 id="Promise-的状态改变，是不可逆的"><a href="#Promise-的状态改变，是不可逆的" class="headerlink" title="Promise 的状态改变，是不可逆的"></a>Promise 的状态改变，是不可逆的</h3><h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>1、promise 有三种状态：等待中、成功、失败。等待中状态可以更改为成功或失败，已经更改过状态后⽆法继续更改（例如从失败改为成功）。</p>
<p>2、promise 实例中需要传⼊⼀个函数，这个函数接收两个参数，执⾏第⼀个参数之后就会改变当前 promise 为「成功」状态，执⾏第⼆个参数之后就会变为「失败」状态。</p>
<p>3、通过 .then ⽅法，即可在上⼀个 promise 达到成功时继续执⾏下⼀个函数或 promise。同时通过 resolve 或 reject 时传⼊参数，即可给下⼀个函数或 promise 传⼊初始值。</p>
<p>4、失败的 promise，后续可以通过 promise 自带的 .catch ⽅法或是 .then ⽅法的第⼆个参数进⾏捕获。</p>
<h3 id="Promise-规范"><a href="#Promise-规范" class="headerlink" title="Promise 规范"></a>Promise 规范</h3><p>Promise 是⼀个拥有 then ⽅法的对象或函数。任何符合 promise 规范的对象或函数都可以成为 Promise。</p>
<p>关于 promise 规范的详细解读，可以看下面这个链接：</p>
<ul>
<li>Promises&#x2F;A+ 规范：<a target="_blank" rel="noopener" href="https://promisesaplus.com/">https://promisesaplus.com/</a></li>
</ul>
<p>了解这些常见概念之后，接下来，我们来具体看看 promise 的代码是怎么写的。</p>
<h2 id="Promise-封装定时器"><a href="#Promise-封装定时器" class="headerlink" title="Promise 封装定时器"></a>Promise 封装定时器</h2><h3 id="传统写法"><a href="#传统写法" class="headerlink" title="传统写法"></a>传统写法</h3><p>写法 1：</p>
<pre class="highlight"><span class="line"><span class="comment">// 定义一个异步的延迟函数：异步函数结束1秒之后，再执行cb回调函数</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fun1</span>(<span class="params">cb</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;即将执行cb回调函数&#x27;</span>);</span><br><span class="line">        <span class="title function_">cb</span>();</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 先执行异步函数 fun1，再执行回调函数 myCallback</span></span><br><span class="line"><span class="title function_">fun1</span>(myCallback);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义回调函数</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">myCallback</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是延迟执行的cb回调函数&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>写法 2：（精简版，更常见）</p>
<pre class="highlight"><span class="line"><span class="comment">// 定义一个异步的延迟函数：异步函数结束1秒之后，再执行cb回调函数</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fun1</span>(<span class="params">cb</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(cb, <span class="number">1000</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 先执行异步函数fun1，再执行回调函数</span></span><br><span class="line"><span class="title function_">fun1</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是延迟执行的cb回调函数&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre>

<p>上⾯的例⼦就是最传统的写法，在异步结束后通过传入回调函数的方式执⾏函数。</p>
<p>学习 Promise 之后，我们可以将这个异步函数封装为 Promise，如下。</p>
<h3 id="Promise-写法"><a href="#Promise-写法" class="headerlink" title="Promise 写法"></a>Promise 写法</h3><pre class="highlight"><span class="line"><span class="keyword">function</span> <span class="title function_">myPromise</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(resolve, <span class="number">1000</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 【重要】上面的 myPromise 也可以写成：</span></span><br><span class="line"><span class="comment">function myPromise() &#123;</span></span><br><span class="line"><span class="comment">    return new Promise((resolve) =&gt; &#123;</span></span><br><span class="line"><span class="comment">        setTimeout(() =&gt; &#123;</span></span><br><span class="line"><span class="comment">            resolve();</span></span><br><span class="line"><span class="comment">        &#125;, 1000);</span></span><br><span class="line"><span class="comment">    &#125;);</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 先执行异步函数 myPromise，再执行回调函数</span></span><br><span class="line"><span class="title function_">myPromise</span>().<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是延迟执行的回调函数&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre>

<h2 id="Promise-封装-Ajax-请求"><a href="#Promise-封装-Ajax-请求" class="headerlink" title="Promise 封装 Ajax 请求"></a>Promise 封装 Ajax 请求</h2><h3 id="传统写法-1"><a href="#传统写法-1" class="headerlink" title="传统写法"></a>传统写法</h3><pre class="highlight"><span class="line"><span class="comment">// 封装 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 这里的 &amp;&amp; 符号，意思是：如果传了 fail 参数，就调用后面的 fail()；如果没传 fail 参数，就不调用后面的内容。因为 fail 参数不一定会传。</span></span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 执行 ajax 请求</span></span><br><span class="line"><span class="title function_">ajax</span>(</span><br><span class="line">    <span class="string">&#x27;/a.json&#x27;</span>,</span><br><span class="line">    <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 第一个接口请求成功:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(res));</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 请求失败:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(err));</span><br><span class="line">    &#125;</span><br><span class="line">);</span><br></pre>

<p>上面的传统写法里，定义和执行 ajax 时需要传⼊ success 和 fail 这两个回调函数，进而执行回调函数。</p>
<p>注意看注释，<code>callback &amp;&amp; callback()</code>这种格式的写法，很常见。</p>
<h3 id="Promise-写法-1"><a href="#Promise-写法-1" class="headerlink" title="Promise 写法"></a>Promise 写法</h3><p>有了 Promise 之后，我们不需要传入回调函数，而是：</p>
<ul>
<li><p>先将 promise 实例化；</p>
</li>
<li><p>然后在原来执行回调函数的地方，改为执行对应的改变 promise 状态的函数；</p>
</li>
<li><p>并通过 then … catch 或者 then …then 等写法，实现链式调用，提高代码可读性。</p>
</li>
</ul>
<p>和传统写法相比，promise 在写法上的大致区别是：定义异步函数的时候，将 callback 改为 resolve 和 reject，待状态改变之后，我们在外面控制具体执行哪些函数。</p>
<p>写法 1：</p>
<pre class="highlight"><span class="line"><span class="comment">// 封装 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 这里的 &amp;&amp; 符号，意思是：如果传了 fail 参数，就调用后面的 fail()；如果没传 fail 参数，就不调用后面的内容。因为 fail 参数不一定会传。</span></span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一步：model层的接口封装</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">promiseA</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;xxx_a.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 这里的 res 是接口的返回结果。返回码 retCode 是动态数据。</span></span><br><span class="line">            <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// 接口请求成功时调用</span></span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&#x27;request success&#x27;</span> + res);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 接口请求失败时调用</span></span><br><span class="line">                <span class="title function_">reject</span>(&#123; <span class="attr">retCode</span>: -<span class="number">1</span>, <span class="attr">msg</span>: <span class="string">&#x27;network error&#x27;</span> &#125;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二步：业务层的接口调用。这里的 data 就是 从 resolve 和 reject 传过来的，也就是从接口拿到的数据</span></span><br><span class="line"><span class="title function_">promiseA</span>()</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 resolve 获取正常结果：接口请求成功后，打印接口的返回结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 reject 获取异常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;);</span><br></pre>

<p>上方代码中，当从接口返回的数据<code>data.retCode</code>的值（接口返回码）不同时，可能会走 resolve，也可能会走 reject，这个由你自己的业务决定。</p>
<p>接口返回的数据，一般是<code>&#123; retCode: 0, msg: &#39;qianguyihao&#39; &#125;</code> 这种 json 格式， retCode 为 0 代表请求接口成功，所以前端对应会写<code>if (res.retCode == 0) </code>这样的逻辑。</p>
<p>另外，上面的写法中，是将 promise 实例定义成了一个<strong>函数</strong> <code>promiseA</code>。我们也可以将 promise 实例定义成一个<strong>变量</strong> <code>promiseB</code>，达到的效果和上面的代码是一模一样的。写法如下：（写法上略有区别）</p>
<p>写法 2：</p>
<pre class="highlight"><span class="line"><span class="comment">// 第一步：model层的接口封装</span></span><br><span class="line"><span class="keyword">const</span> promiseB = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">ajax</span>(<span class="string">&#x27;xxx_a.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 这里的 res 是接口的返回结果。返回码 retCode 是动态数据。</span></span><br><span class="line">        <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 接口请求成功时调用</span></span><br><span class="line">            <span class="title function_">resolve</span>(<span class="string">&#x27;request success&#x27;</span> + res);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 接口请求失败时调用</span></span><br><span class="line">            <span class="title function_">reject</span>(&#123; <span class="attr">retCode</span>: -<span class="number">1</span>, <span class="attr">msg</span>: <span class="string">&#x27;network error&#x27;</span> &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二步：业务层的接口调用。这里的 data 就是 从 resolve 和 reject 传过来的，也就是从接口拿到的数据</span></span><br><span class="line">promiseB</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 resolve 获取正常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 reject 获取异常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;);</span><br></pre>

<p>注意，如果你用的是写法 1（将 promise 实例定义为函数），则调用 promise 的时候是<code>promiseA().then()</code>，如果你用的是写法 2（将 promise 实例定位为函数），则调用的时候用的是<code>promiseB.then()</code>。写法 1 多了个括号，不要搞混了。</p>
<h2 id="处理-reject-失败状态的两种写法"><a href="#处理-reject-失败状态的两种写法" class="headerlink" title="处理 reject 失败状态的两种写法"></a>处理 reject 失败状态的两种写法</h2><p>我们有两种写法可以捕获并处理 reject 异常状态：</p>
<ul>
<li><p>写法 1：通过 catch 方法捕获 状态变为已 reject 时的 promise</p>
</li>
<li><p>写法 2：then 可以传两个参数，第⼀个参数为 resolve 后执⾏，第⼆个参数为 reject 后执⾏。</p>
</li>
</ul>
<h3 id="代码格式"><a href="#代码格式" class="headerlink" title="代码格式"></a>代码格式</h3><p>这两种写法的<strong>代码格式</strong>如下：</p>
<pre class="highlight"><span class="line"><span class="comment">// 第一步：model层的接口封装</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">promiseA</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 这里做异步任务（比如 ajax 请求接口，或者定时器）</span></span><br><span class="line">				...</span><br><span class="line">        ...</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onResolve = <span class="keyword">function</span> (<span class="params">res</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> onReject = <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 写法1：通过 catch 方法捕获 状态变为已拒绝时的 promise</span></span><br><span class="line"><span class="title function_">promiseA</span>().<span class="title function_">then</span>(onResolve).<span class="title function_">catch</span>(onReject);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 写法2：then 可以传两个参数，第⼀个参数为 resolve 后执⾏，第⼆个参数为 reject 后执⾏</span></span><br><span class="line"><span class="title function_">promiseA</span>().<span class="title function_">then</span>(onResolve, onReject);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 【错误写法】写法3：通过 try catch 捕获 状态变为已拒绝时的 promise</span></span><br><span class="line"><span class="comment">// 这种写法是错误的，因为 try catch只能捕获同步代码里的异常，而  promise.reject() 是异步代码。</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="title function_">promiseA</span>().<span class="title function_">then</span>(onResolve);</span><br><span class="line">&#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">    <span class="comment">// 语法上，catch必须要传入一个参数，否则报错</span></span><br><span class="line">    <span class="title function_">onReject</span>(e);</span><br><span class="line">&#125;</span><br></pre>

<p>如注释所述：前面的段落里，我们捕获 reject 异常用的就是写法 1。如果你写法 2 也是可以的。</p>
<p>需要注意的是，上面的写法 3 是错误的。运行之后，控制台会报如下错误：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20210430_1553.png" class="lozad post-image"src="http://img.smyhvae.com/20210430_1553.png"></p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/xiaoluodecai/article/details/107297404">解释如下</a>：</p>
<p>try-catch 主要用于捕获异常，注意，这里的异常是指<strong>同步</strong>函数的异常。如果 try 里面的异步方法出现了异常，此时 catch 是无法捕获到异常的。</p>
<p>原因是：当异步函数抛出异常时，对于宏任务而言，执行函数时已经将该函数推入栈，此时并不在 try-catch 所在的栈，所以 try-catch 并不能捕获到错误。对于微任务而言（比如 promise）promise 的构造函数的异常只能被自带的 reject 也就是.catch 函数捕获到。</p>
<p>（2）写法 1 中，<code>promiseA().then().catch()</code>和<code>promiseA().catch().then()</code>区别在于：前者可以捕获到 <code>then</code> 里面的异常，后者不可以。</p>
<h3 id="代码举例"><a href="#代码举例" class="headerlink" title="代码举例"></a>代码举例</h3><p>这两种写法的<strong>代码举例</strong>如下：</p>
<pre class="highlight"><span class="line"><span class="keyword">function</span> <span class="title function_">promiseA</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 这里做异步任务（比如 ajax 请求接口，或者定时器）</span></span><br><span class="line">            ...</span><br><span class="line">            ...</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 写法1</span></span><br><span class="line"><span class="title function_">promiseB</span>()</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 resolve 获取正常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求成功时，走这里&#x27;</span>);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 reject 获取异常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求失败时，走这里&#x27;</span>);</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">finally</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;无论接口请求成功与否，都会走这里&#x27;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 写法 2：（和写法 1 等价）</span></span><br><span class="line"><span class="title function_">promiseB</span>()</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 从 resolve 获取正常结果</span></span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求成功时，走这里&#x27;</span>);</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 从 reject 获取异常结果</span></span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求失败时，走这里&#x27;</span>);</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    .<span class="title function_">finally</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;无论接口请求成功与否，都会走这里&#x27;</span>);</span><br><span class="line">    &#125;);</span><br></pre>

<p><strong>代码解释</strong>：写法 1 和写法 2 的作用是完全等价的。只不过，写法 2 是把 catch 里面的代码作为 then 里面的第二个参数而已。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>了解这些内容之后， 你已经对 Promise 有了基本了解。下一篇文章，我们来讲一讲 Promise 在实战开发的常见用法。</p>
<h2 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h2><ul>
<li><p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/29235579">当面试官问你 Promise 的时候，他究竟想听到什么？</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/dennisj/p/12660388.html">手写一个 Promise&#x2F;A+,完美通过官方 872 个测试用例</a></p>
</li>
</ul>
<h2 id="我的公众号"><a href="#我的公众号" class="headerlink" title="我的公众号"></a>我的公众号</h2><p>想学习<strong>更多技能</strong>？不妨关注我的微信公众号：<strong>千古壹号</strong>（id：<code>qianguyihao</code>）。</p>
<p>扫一扫，你将发现另一个全新的世界，而这将是一场美丽的意外：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="https://img.smyhvae.com/20200102.png" class="lozad post-image"src="https://img.smyhvae.com/20200102.png"></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/05-Promise%E5%85%A5%E9%97%A8%E8%AF%A6%E8%A7%A3/">
            https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/05-Promise%E5%85%A5%E9%97%A8%E8%AF%A6%E8%A7%A3/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/04-%E5%90%8C%E6%BA%90%E5%92%8C%E8%B7%A8%E5%9F%9F/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">04-同源和跨域 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/06-Promise%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">06-Promise的链式调用 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81-Promise%EF%BC%9F"><span class="toc-text">为什么需要 Promise？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">回调的定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="toc-text">回调的缺点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E4%BB%8B%E7%BB%8D%E5%92%8C%E4%BC%98%E7%82%B9"><span class="toc-text">Promise 的介绍和优点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%94%A8%E6%B3%95%E5%92%8C%E7%8A%B6%E6%80%81"><span class="toc-text">Promise 对象的用法和状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Promise-%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%AD%A5%E9%AA%A4"><span class="toc-text">使用 Promise 的基本步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%AF%B9%E8%B1%A1%E7%9A%84-3-%E4%B8%AA%E7%8A%B6%E6%80%81"><span class="toc-text">promise 对象的 3 个状态</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%A0%E7%82%B9%E8%A1%A5%E5%85%85"><span class="toc-text">几点补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#new-Promise-%E6%98%AF%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81"><span class="toc-text">new Promise() 是同步代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E4%B8%80%E6%97%A6%E6%94%B9%E5%8F%98%EF%BC%8C%E5%B0%B1%E4%B8%8D%E8%83%BD%E5%86%8D%E5%8F%98"><span class="toc-text">Promise 的状态一旦改变，就不能再变</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E6%94%B9%E5%8F%98%EF%BC%8C%E6%98%AF%E4%B8%8D%E5%8F%AF%E9%80%86%E7%9A%84"><span class="toc-text">Promise 的状态改变，是不可逆的</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E8%A7%84%E8%8C%83"><span class="toc-text">Promise 规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="toc-text">Promise 封装定时器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">Promise 封装 Ajax 请求</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95-1"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95-1"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81%E7%9A%84%E4%B8%A4%E7%A7%8D%E5%86%99%E6%B3%95"><span class="toc-text">处理 reject 失败状态的两种写法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F"><span class="toc-text">代码格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%BE%E4%BE%8B"><span class="toc-text">代码举例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="toc-text">参考链接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81-Promise%EF%BC%9F"><span class="toc-text">为什么需要 Promise？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">回调的定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E7%9A%84%E7%BC%BA%E7%82%B9"><span class="toc-text">回调的缺点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E4%BB%8B%E7%BB%8D%E5%92%8C%E4%BC%98%E7%82%B9"><span class="toc-text">Promise 的介绍和优点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%94%A8%E6%B3%95%E5%92%8C%E7%8A%B6%E6%80%81"><span class="toc-text">Promise 对象的用法和状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Promise-%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%AD%A5%E9%AA%A4"><span class="toc-text">使用 Promise 的基本步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#promise-%E5%AF%B9%E8%B1%A1%E7%9A%84-3-%E4%B8%AA%E7%8A%B6%E6%80%81"><span class="toc-text">promise 对象的 3 个状态</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%A0%E7%82%B9%E8%A1%A5%E5%85%85"><span class="toc-text">几点补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#new-Promise-%E6%98%AF%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81"><span class="toc-text">new Promise() 是同步代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E4%B8%80%E6%97%A6%E6%94%B9%E5%8F%98%EF%BC%8C%E5%B0%B1%E4%B8%8D%E8%83%BD%E5%86%8D%E5%8F%98"><span class="toc-text">Promise 的状态一旦改变，就不能再变</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81%E6%94%B9%E5%8F%98%EF%BC%8C%E6%98%AF%E4%B8%8D%E5%8F%AF%E9%80%86%E7%9A%84"><span class="toc-text">Promise 的状态改变，是不可逆的</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E8%A7%84%E8%8C%83"><span class="toc-text">Promise 规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85%E5%AE%9A%E6%97%B6%E5%99%A8"><span class="toc-text">Promise 封装定时器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">Promise 封装 Ajax 请求</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95-1"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95-1"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81%E7%9A%84%E4%B8%A4%E7%A7%8D%E5%86%99%E6%B3%95"><span class="toc-text">处理 reject 失败状态的两种写法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F"><span class="toc-text">代码格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%BE%E4%BE%8B"><span class="toc-text">代码举例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="toc-text">参考链接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
